package sc.hibernate.config;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

/**
 * TODO singleton de sessionFactory plutot que session
 * @author raisced
 *
 */
public class HibernateSession {
	private static SessionFactory sessionFactory; 
	private ServiceRegistry serviceRegistry;
	
	private HibernateSession(){
		try{
			// This step will read hibernate.cfg.xml and prepare hibernate for use
			Configuration configuration = new Configuration(); 
		    configuration.configure(); 
		    serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();         
		    sessionFactory = configuration.buildSessionFactory(serviceRegistry); 
		}catch(Exception e){
			System.out.println(e.getMessage());
		}
	}
		
	/**
	 * Get the single Hibernate session
	 * 
	 * @return session
	 */
	public static SessionFactory getSessionFactory() {
		if (sessionFactory == null)
			new HibernateSession(); // instanciation retardée
		return sessionFactory;
	}
}
